package com.hfzy.ihk.web.userCenter.controller;


import com.hfzy.ihk.facade.userCenter.entity.Priv;
import com.hfzy.ihk.facade.userCenter.entity.Resource;
import com.hfzy.ihk.web.oauth.client.table.PageTableHandler;
import com.hfzy.ihk.web.oauth.client.table.PageTableRequest;
import com.hfzy.ihk.web.oauth.client.table.PageTableResponse;
import com.hfzy.ihk.web.userCenter.biz.PrivBiz;
import com.hfzy.ihk.web.userCenter.mapper.PrivHasResourceMapper;
import com.hfzy.ihk.web.userCenter.mapper.PrivMapper;
import com.hfzy.ihk.web.userCenter.mapper.ResourceMapper;
import com.hfzy.ihk.web.userCenter.mapper.UserHasResourceMapper;
import com.hfzy.ihk.web.userCenter.vo.PrivDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用于集成spring security,权限表 前端控制器
 * </p>
 *
 * @author chenzesen
 * @since 2018-12-28
 */
@RestController
@RequestMapping("priv")
@Slf4j
public class PrivController {

    @Autowired
    private PrivMapper privMapper ;

    @Autowired
    PrivBiz privBiz;

    @Autowired
    ResourceMapper resourceMapper;

    @Autowired
    PrivHasResourceMapper privHasResourceMapper;

    @Autowired
    UserHasResourceMapper userHasResourceMapper;


    /**
     * 权限页
     * @param view
     * @return
     */
    @RequestMapping("list")
    public ModelAndView saveUser(ModelAndView view) {
        view.setViewName("page/priv/privList");
        return view;
    }


    /**
     * 打开增加页面
     * @param request
     * @param response
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = {"/addPage"})
    public ModelAndView addPage(HttpServletRequest request, HttpServletResponse response, ModelAndView modelAndView) {
        modelAndView.setViewName("page/priv/addPriv");
        return modelAndView;
    }

    /**
     * 打开更新页面
     * @param request
     * @param response
     * @param modelAndView
     * @param id
     * @return
     */
    @RequestMapping(value = {"/updatePage"})
    public ModelAndView updatePage(HttpServletRequest request, HttpServletResponse response, ModelAndView modelAndView,Long id) {
        modelAndView.setViewName("page/priv/updatePriv");
        modelAndView.addObject("id",id);
        Priv priv = privMapper.selectById(id);
        modelAndView.addObject("priv",priv);
        return modelAndView;
    }




    /**
     * 查询权限
     * @param request
     * @return
     */
    @RequestMapping("queryPriv")
    public PageTableResponse listRoles(PageTableRequest request) {
        request.setOffset((request.getOffset()-1)*request.getLimit());
        return new PageTableHandler(new PageTableHandler.CountHandler() {

            @Override
            public int count(PageTableRequest request) {
                return privMapper.count(request.getParams());
            }
        }, new PageTableHandler.ListHandler() {

            @Override
            public List<Priv> list(PageTableRequest request) {
                List<Priv> list = privMapper.list(request.getParams(), request.getOffset(), request.getLimit());
                return list;
            }
        }).handle(request);
    }


    /**
     * 删除同时删除所有关联关系
     * @param id
     * @return
     */
    @RequestMapping("delete")
    public Map<String,Object> delete(Long id) {
        Map<String,Object> map = new HashMap<>();
        try {
            privBiz.deletePriv(id);
            map.put("code",1);
            map.put("msg","删除成功");
        }catch (Exception e){
            log.error("......删除权限失败",e);
            map.put("code",1);
            map.put("msg","删除成功");
        }
        return map;
    }


    /**
     * 查询所有菜单
     * @return
     */
    @RequestMapping("getAllMenu")
    public Map<String,Object> getAllMenu(String id,String userId){

        Map<String,Object> map = new HashMap<>();
        List<Resource> resourcesAll = resourceMapper.allListParents();

        List<Integer> privHasResource = null;
        List<Integer> userIdHasResource = null;
        if(id!=null&&!id.equals("")) {
            privHasResource = privHasResourceMapper.queryRrsourceByPriId(Long.valueOf(id));
        }

        if(userId!=null&&!userId.equals("")){
            userIdHasResource= userHasResourceMapper.queryRrsourceByUserId(Long.valueOf(userId));

        }
        map.put("dataTree",setMenu(0L,resourcesAll,privHasResource,userIdHasResource));
        Map statusMap = new HashMap();
        statusMap.put("code",0);
        statusMap.put("message","操作成功");
        map.put("status",statusMap);
        return map;

    }

    /**
     * 递归方法
     * @param pId
     * @param resourcesAll
     * @return
     */
    public List<Map<String,Object>>  setMenu(Long pId,List<Resource> resourcesAll,List<Integer> privHasResource,List<Integer> userHasResource){
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        for (Resource per : resourcesAll) {
            if(pId.intValue()==per.getParentId()) {
                Map<String,Object> map = new HashMap<>();
                map.put("treeId",per.getId());
                map.put("title",per.getLabel());
                map.put("parentId",per.getParentId());
                map.put("children",setMenu(per.getId().longValue(),resourcesAll,privHasResource,userHasResource));
                Map<String,Object> ratioMap = new HashMap<>();
                if(privHasResource!=null){
                    if(privHasResource.contains(per.getId())){
                        ratioMap.put("type","0");
                        ratioMap.put("isChecked","1");
                    }else{
                        ratioMap.put("type","0");
                        ratioMap.put("isChecked","0");
                    }
                }else if(userHasResource!=null){
                    if(userHasResource.contains(per.getId())){
                        ratioMap.put("type","0");
                        ratioMap.put("isChecked","1");
                    }else{
                        ratioMap.put("type","0");
                        ratioMap.put("isChecked","0");
                    }
                }else{
                    ratioMap.put("type","0");
                    ratioMap.put("isChecked","0");
                }
                map.put("checkArr",ratioMap);
                list.add(map);
            }

        }
        return list;
    }

    @RequestMapping("savePriv")
    public Map<String,Object> savePriv( PrivDto privDto) {
        Map<String,Object> map = new HashMap<>();
        try {
            privBiz.savePriv(privDto);
            map.put("code", 1);
            map.put("msg", "保存成功");
        }catch (IllegalArgumentException e1){
            map.put("code",0);
            map.put("msg",e1.getMessage());

        }catch (Exception e){
            log.error("保存权限失败",e);
            map.put("code",0);
            map.put("msg","保存失败");

        }
        return map;
    }

    @RequestMapping("getAllPriv")
    public List<Priv> getAllPriv(){
        return privMapper.list(new HashMap<String,Object>() {
        }, null, null);
    }



}
